#import "Common.h"
#import "DataType.h"
#import "LayerResult.h"
#import "InvaderBase.h"
#import "LayerSelMode.h"
#import "LayerGame.h"
#import "LayerStore.h"
#import "SpellSlot.h"
#import "BtnGold.h"
#import "DataSL.h"
#import "OpenFeint/OFSocialNotificationApi.h"

CGPoint sResultBtnPos[3] = { ccp(70,30), ccp(240,30), ccp(410,30) };
NSString* sResultBtnLabel[3] = { @"BtnBack", @"BtnRetry", @"BtnShop" };

@implementation SceneResult

-(id) init
{
	if ((self = [super init]))
		[self addChild:[LayerResult node]];
	return self;
}

@end

@implementation LayerResult

-(id)init
{
	if ((self = [super init]))
	{
		// 处理数据
		if(gCurScore.gameMode == GM_Time) { // 时间模式
			// 高分
			[gGCManager reportScore:gCurScore.score category:1];
			if(gCurScore.score > gGlobalData.highScoreTime) {
				gGlobalData.highScoreTime = gCurScore.score;
			}
				
			// 分数
			if(gCurScore.score >= 1500000) {	// 成就5，大师
				[gGCManager reportAm:5 percent:100];
			}
			if(gCurScore.score >= 1200000) {	// 成就4，精英
				[gGCManager reportAm:4 percent:100];
			}
			if(gCurScore.score >= 1000000) {	// 成就3，专家
				[gGCManager reportAm:3 percent:100];
			}
			if(gCurScore.score >= 800000) {		// 成就2，学徒
				[gGCManager reportAm:2 percent:100];
			}
			if(gCurScore.score >= 500000) {		// 成就1，新手
				[gGCManager reportAm:1 percent:100];
			}
			if(gCurScore.score < 0) {			// 成就21，睡着了
				[gGCManager reportAm:20 percent:100];
			}
		} else if(gCurScore.gameMode == GM_Survival) {	// 生存模式
			// 高分
			[gGCManager reportScore:gCurScore.lastInSurvival category:2];
			if(gCurScore.lastInSurvival > gGlobalData.highScoreSurvival) {	
				gGlobalData.highScoreSurvival = gCurScore.lastInSurvival;
			}
			// 持续时间
			if(gCurScore.lastInSurvival >= 240) {	// 成就12，不可能
				[gGCManager reportAm:12 percent:100];
			}
			if(gCurScore.lastInSurvival >= 180) {	// 成就11，生存者
				[gGCManager reportAm:11 percent:100];
			}
			if(gCurScore.lastInSurvival >= 120) {	// 成就10，组织者
				[gGCManager reportAm:10 percent:100];
			}
		}
		
		// 侵略者数量
		for(int i=0; i<INVADERS_COUNT; i++) {
			gGlobalData.invadersCount[i] += gCurScore.invadersCount[i];
			
			if(i == IT_Bad) {
				if(gGlobalData.invadersCount[i] >= 50) {
					[gGCManager reportAm:21 percent:100];	// 惨烈
				}
				else if(gCurScore.invadersCount[i] == 0) {
					gGlobalData.perfectFinish++;
					[gGCManager reportAm:13 percent:MIN(100,gGlobalData.perfectFinish*10)];	// 完美
				}
			}
			
			if(i == IT_Good && gCurScore.invadersCount[i] >= 100) { // 成就16，敛财者
				[gGCManager reportAm:15 percent:100];
			}
			
			gGlobalData.totalInvaders += gCurScore.invadersCount[i];
		}
		
		[gGCManager reportAm:9 percent:MIN(100,gGlobalData.totalInvaders/1000)];	// 成就9，将军
		[gGCManager reportAm:8 percent:MIN(100,gGlobalData.totalInvaders/500)];		// 成就8，上校
		[gGCManager reportAm:7 percent:MIN(100,gGlobalData.totalInvaders/100)];		// 成就7，上尉
		[gGCManager reportAm:6 percent:MIN(100,gGlobalData.totalInvaders/50)];		// 成就6，中士
		
		// 游戏次数
		gGlobalData.playTimes++;
		[gGCManager reportAm:19 percent:MIN(100,gGlobalData.playTimes*2)];		// 成就20，上瘾了
		[gGCManager reportAm:18 percent:MIN(100,gGlobalData.playTimes*5)];		// 成就19，忠实粉丝
		[gGCManager reportAm:17 percent:MIN(100,gGlobalData.playTimes*10)];		// 成就18，粉丝
		
		// 金币
		mAchieve = [LevelAchievements node];
		int totalGold = 0;
		if(gCurScore.score > 1000000)
			totalGold = 150+(gCurScore.score-1000000)/10000*3;
		else if(gCurScore.score > 500000)
			totalGold = 50+(gCurScore.score-500000)/5000;
		else if(gCurScore.score > 0)
			totalGold = gCurScore.score/10000;
		else
			totalGold = 0;

		totalGold += gCurScore.invadersCount[IT_Gold]*5+[mAchieve getAllScore];
		gGlobalData.gold += totalGold;

		gSaveData();

		[self setIsTouchEnabled:YES];

		CCSprite* bg = [CCSprite spriteWithFile:@"background.png"];
		bg.position = gPointCenter;
		bg.opacity = 100;
		[self addChild:bg];
		
		// Title
		CCLabelTTF* title = [CCLabelTTF labelWithString:NSLocalizedString(@"ResultTitle",nil)
											   fontName:gFontName
											   fontSize:30];
		title.position = ccp(240,300);
		title.color = ccGREEN;
		[self addChild:title];

		// Enemies
		CCLabelTTF* labelEnimies = [CCLabelTTF labelWithString:NSLocalizedString(@"Invaders",nil)
													  fontName:gFontName
													  fontSize:16];
		labelEnimies.color = ccYELLOW;
		labelEnimies.anchorPoint = gAnchorLeft;
		labelEnimies.position = ccp(30+gSettingData.startPosX,265);
		[self addChild:labelEnimies];
		
		InvaderType type[5] = { IT_Normal_1, IT_Normal_2, IT_Good, IT_Bad, IT_Gold };
		CGPoint startPos = ccp(30+gSettingData.startPosX, 240);
		
		for(int i=0; i<5; i++) {
			InvaderData& id = gInvadersData[type[i]];
			CCSprite* invader = [CCSprite spriteWithSpriteFrame:[id.frameArr objectAtIndex:0]];
			int x = startPos.x+i*77;
			int y = startPos.y;
			invader.position = ccp(x,y);
			invader.anchorPoint = gAnchorLeft;
			invader.scale = 0.5;
			[self addChild:invader];
			CCLabelTTF* labelEnimyCount = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"x %d", gCurScore.invadersCount[type[i]]]
															 fontName:gFontName
															 fontSize:16];
			labelEnimyCount.color = ccYELLOW;
			labelEnimyCount.anchorPoint = gAnchorLeft;
			labelEnimyCount.position = ccp(x+30,y);
			[self addChild:labelEnimyCount];
		}

		// Achievement
		CCLabelTTF* labelAchievement = [CCLabelTTF labelWithString:NSLocalizedString(@"Achievements",nil) fontName:gFontName fontSize:16];
		labelAchievement.color = ccYELLOW;
		labelAchievement.anchorPoint = gAnchorLeft;
		labelAchievement.position = ccp(30+gSettingData.startPosX,210);
		[self addChild:labelAchievement];
		
		mAchieve.position = ccp(50+gSettingData.startPosX,200);
		[self addChild:mAchieve z:500];
		
		CCSprite* spector = [CCSprite spriteWithFile:@"resultspector.png"];
		spector.position = ccp(220+gSettingData.startPosX,140);
		[self addChild:spector];
		
		// Total Score
		CCLabelTTF* labelTotal = [CCLabelTTF labelWithString:[NSString stringWithFormat:NSLocalizedString(@"ResultScore",nil), commaprint(gCurScore.score)]
													fontName:gFontName
													fontSize:20];
		labelTotal.color = ccYELLOW;
		labelTotal.anchorPoint = gAnchorLeft;
		labelTotal.position = ccp(30+gSettingData.startPosX,110);
		[self addChild:labelTotal];
		
		// Last Time
		if(gCurScore.gameMode == GM_Survival) {
			CCLabelTTF* labelLast = [CCLabelTTF labelWithString:[NSString stringWithFormat:NSLocalizedString(@"ResultLastTime",nil), gCurScore.lastInSurvival]
													   fontName:gFontName
													   fontSize:20];
			labelLast.color = ccYELLOW;
			labelLast.anchorPoint = gAnchorRight;
			labelLast.position = ccp(390+gSettingData.startPosX,110);
			[self addChild:labelLast];
		}
			
		// Get Money
		CCSprite* goldIcon = [CCSprite spriteWithFile:@"GoldCoin.png"];
		goldIcon.position = ccp(30+gSettingData.startPosX,77);
		goldIcon.anchorPoint = gAnchorLeft;
		[self addChild:goldIcon];
		
		CCLabelTTF* labelGold = [CCLabelTTF labelWithString:[NSString stringWithFormat:@": %s", commaprint(totalGold)]
												   fontName:gFontName
												   fontSize:20];
		labelGold.color = ccYELLOW;
		labelGold.anchorPoint = gAnchorLeft;
		labelGold.position = ccp(55+gSettingData.startPosX,77);
		[self addChild:labelGold];

		BtnGold* gold = [BtnGold node];
		gold.position = ccp(gSettingData.spellInRight ? 450:30,290);
		[self addChild:gold];
		
		CCTexture2D* btn_02 = [[CCTextureCache sharedTextureCache] addImage:@"btn-02.png"];
		CCTexture2D* btn_02_s = [[CCTextureCache sharedTextureCache] addImage:@"btn-02-s.png"];
		
		CCSprite *item, *itemDown;
		CCMenuItemSprite* menuItem;
		CCMenu* menu = [CCMenu menuWithItems:NULL];
		menu.position = CGPointZero;
		[self addChild:menu];
		for(int i = 0; i < 3; i++)
		{
			item = [CCSprite spriteWithTexture:btn_02];
			itemDown = [CCSprite spriteWithTexture:btn_02_s];
			menuItem = [CCMenuItemSprite itemFromNormalSprite:item
											   selectedSprite:itemDown
													   target:self
													 selector:@selector(callMenu:)];
			menuItem.position = sResultBtnPos[i];
			CCLabelTTF* itemLabel = [CCLabelTTF labelWithString:NSLocalizedString(sResultBtnLabel[i],nil)
													   fontName:gFontName
													   fontSize:16];
			itemLabel.position = ccp(item.contentSize.width/2,item.contentSize.height/2+2);
			[menuItem addChild:itemLabel];
			[menu addChild:menuItem z:i+1000];
		}
		
		// Submit Score
		CCLabelTTF* labelSubmit = [CCLabelTTF labelWithString:NSLocalizedString(@"ResultSubmit",nil)
													 fontName:gFontName
													 fontSize:20];
		labelSubmit.color = ccYELLOW;
		labelSubmit.anchorPoint = gAnchorRight;
		labelSubmit.position = ccp(335+gSettingData.startPosX,77);
		[self addChild:labelSubmit];
		
		// facebook
		menuItem = [CCMenuItemImage itemFromNormalImage:@"btn-facebook.png" selectedImage:@"btn-facebook.png" target:self selector:@selector(callMenu:)];
		menuItem.anchorPoint = gAnchorRight;
		menuItem.position = ccp(370+gSettingData.startPosX,75);
		[menu addChild:menuItem z:1003];
		
		// twitter
		menuItem = [CCMenuItemImage itemFromNormalImage:@"btn-twitter.png" selectedImage:@"btn-twitter.png" target:self selector:@selector(callMenu:)];
		menuItem.anchorPoint = gAnchorRight;
		menuItem.position = ccp(400+gSettingData.startPosX,75);
		[menu addChild:menuItem z:1004];
	}
	return self;
}

-(void) callMenu:(CCMenuItem*)sender
{
	int id = [sender zOrder];
	[[SimpleAudioEngine sharedEngine] playEffect:SOUND_BTN01];
	
	switch(id)
	{
		case 1000:		// back
			[[CCDirector sharedDirector] replaceScene:
			 [CCTransitionFade transitionWithDuration:0.5 scene:[SceneSelMode node]]];
			break;
		case 1001:		// retry
			[[CCDirector sharedDirector] replaceScene:
			 [CCTransitionFade transitionWithDuration:0.5 scene:[[SceneGame alloc] initWithMode:gCurScore.gameMode]]];
			break;
		case 1002:		// store
		{	
			[self onExit];
			LayerStore* store = [[[LayerStore alloc] initWithParent:self] autorelease];
			CCScene* scene = [[CCDirector sharedDirector] runningScene];
			[scene addChild:store z:30000];
			break;
		}
		case 1003:		// facebook
		case 1004: 		// twitter
		{
		   NSString* text;
		   if(gCurScore.gameMode == GM_Time)
			   text = [NSString stringWithFormat:NSLocalizedString(@"SocialPostClassic",nil), commaprint(gCurScore.score)];
		   else
			   text = [NSString stringWithFormat:NSLocalizedString(@"SocialPostSurvival",nil), gCurScore.lastInSurvival];

		   [OFSocialNotificationApi sendWithPrepopulatedText:text originalMessage:nil imageNamed:nil];
			if(!gGlobalData.sendToSocial) { // 成就17，社交
				[gGCManager reportAm:16 percent:100];
				gGlobalData.sendToSocial = true;
				gSaveData();
			}
//			}
			break;
		}
	}
}

-(void)registerWithTouchDispatcher
{
	[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
}

-(BOOL)ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)evt
{
	[mAchieve showDescription:touch];
	return NO;
}

-(void)onEnter
{
	if(mSpell)
		[self removeChild:mSpell cleanup:true];
	mSpell = [SpellSlot node];
	[self addChild:mSpell];
	[super onEnter];
}

@end
